package utils

import (
	"fmt"
	"github.com/gogf/gf/v2/util/grand"
	"golang.org/x/crypto/bcrypt"
)

// PasswordHash Hash加密
func PasswordHash(pwd string, salts ...string) (string, error) {
	if len(salts) > 0 {
		pwd += salts[0]
	}
	pwdHash, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost)
	if err != nil {
		return "", err
	}
	return string(pwdHash), nil
}

// PasswordVerify 验证HASH密码有效性
func PasswordVerify(pwdHash string, pwd string, salts ...string) bool {
	if len(salts) > 0 {
		pwd += salts[0]
	}
	return bcrypt.CompareHashAndPassword(
		[]byte(pwdHash), []byte(pwd),
	) == nil
}

// NewAccount 生成新账户
func NewAccount(ps ...string) string {
	var prefix string
	if len(ps) > 0 {
		prefix = ps[0]
	}
	return fmt.Sprintf(`%s%s-%d`, prefix, grand.S(5), RandInt(4))
}

// GenPasswordHash 生成Hash密码
func GenPasswordHash(password ...string) (string, string, error) {
	var (
		pwd, salt = grand.S(8), grand.S(6) // 初始化密码和密码盐
	)
	// 指定密码
	if len(password) > 0 {
		pwd = password[0]
	}
	// 生成HASH值
	hash, err := PasswordHash(pwd, salt)
	if err != nil {
		return "", "", fmt.Errorf(`gen password failed %s`, err.Error())
	}
	return hash, salt, nil
}
